package Java7_Concurrency_Cookbook.thread_executor_framework.scheduled_at_fixed_rate;

import java.util.Date;
import java.util.concurrent.*;

/**
 * ScheduledThreadPoolExecutor类提供了scheduleAtFixedRate()方法来执行周期性任务<br/>
 * 区别于 scheduleWithFixedDelay(), 表示每次任务执行结束后延迟 X 秒再次执行<br/>
 * 默认情况下, executor.shutdown() 之后定时任务就结束了.
 * 可以通过 executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
 * 来设置 executor.shutdown() 之后定时任务继续执行.
 * @author lixiangke
 * @date 2017/11/18
 */
public class Main {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
        System.out.printf("Main: Starting at: %s\n", new Date());
        Task task = new Task("Zoom");
        ScheduledFuture<?> result = executor.scheduleAtFixedRate(task,
                1, 2, TimeUnit.SECONDS);

        for (int i = 0; i < 30; i++) {
            // 任务到下一次执行所要等待的时间
            System.out.printf("Main: Delay: %d \n", result.getDelay(TimeUnit.MILLISECONDS));
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("executor.shutdown()");
        executor.shutdown();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("Main: Finished at: %s\n", new Date());
    }
}
